package com.yy.example.jpa.test;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.List;

/**
 * 动态创建表名..
 *
 * @author Lizhong
 * @date 2019/7/23
 */
@Component
// @EnableScheduling
public class Scheduling {
    @Autowired

    EntityManager entityManager;

    @Autowired
    DataSource dataSource;
    // DataSourceInitializedPublisher
    @Resource
    @Qualifier("dataSourceInitializedPublisher")
    BeanPostProcessor beanPostProcessor;

    @Autowired
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean;

    @Autowired
    DynamicRepository dynamicRepository;


    @Scheduled(cron = "0 0 0 1 * ?")
    public void run() throws Exception {
            System.out.println("等待");
            // DynamicTable dynamicTable = entityManager.;
           /* Class<? extends BeanPostProcessor> aClass = beanPostProcessor.getClass();
            Method isInitializingDatabase = aClass.getDeclaredMethod("isInitializingDatabase", DataSource.class);
            isInitializingDatabase.setAccessible(true);
            isInitializingDatabase.invoke(beanPostProcessor,dataSource);
            Method[] methods = aClass.getMethods();*/
            // beanPostProcessor.postProcessAfterInitialization(localContainerEntityManagerFactoryBean,null);

            localContainerEntityManagerFactoryBean.afterPropertiesSet();
            // localContainerEntityManagerFactoryBean.createNativeEntityManagerFactory();
            /*Class<? extends LocalContainerEntityManagerFactoryBean> aClass = localContainerEntityManagerFactoryBean.getClass();
            Method createNativeEntityManagerFactory = aClass.getDeclaredMethod("createNativeEntityManagerFactory");
            createNativeEntityManagerFactory.setAccessible(true);
            createNativeEntityManagerFactory.invoke(localContainerEntityManagerFactoryBean);*/
            System.out.println("结束**准备插入");
            dynamicRepository.save(new DynamicTable(null, RandomUtils.nextInt() + "", RandomUtils.nextBoolean() + "",true));
            Thread.currentThread().sleep(3000);
            List<DynamicTable> count = dynamicRepository.findAll();
            System.out.println(count.get(0));
            System.out.println(count);
    }
}
